package com.oscarmovie.action;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.oscarmovie.Constants;
import com.oscarmovie.model.Award;
import com.oscarmovie.model.Calendar;
import com.oscarmovie.model.Category;
import com.oscarmovie.model.Comment;
import com.oscarmovie.model.Country;
import com.oscarmovie.model.Image;
import com.oscarmovie.model.ImageMovie;
import com.oscarmovie.model.Language;
import com.oscarmovie.model.Movie;
import com.oscarmovie.model.Mpr;
import com.oscarmovie.model.Mpac;
import com.oscarmovie.model.Music;
import com.oscarmovie.model.Paging;
import com.oscarmovie.model.Person;
import com.oscarmovie.model.DescriptionMovie;
import com.oscarmovie.model.Role;
import com.oscarmovie.model.Video;
import com.oscarmovie.service.CalendarService;
import com.oscarmovie.service.CategoryService;
import com.oscarmovie.service.CommentService;
import com.oscarmovie.service.CountryService;
import com.oscarmovie.service.LanguageService;
import com.oscarmovie.service.MovieService;
import com.oscarmovie.service.MpacService;
import com.oscarmovie.service.MprService;
import com.oscarmovie.service.PlotService;
import com.oscarmovie.service.VideoService;

public class MovieAction {
	private static final String OUT_SEPARATOR = ";";
	private static final String IN_SEPARATOR = ",";
	
	private static final long serialVersionUID = 1L;
	private int scountss;
	// services//////////////////////////////////////////////////////////////////////////
	private MovieService movieService;
	private CategoryService categoryService;
	private CountryService countryService;
	private LanguageService languageService;
	private CalendarService calendarService;
	private PlotService plotService;
	private CommentService commentService;

	// 初始化界面基础数据
	private List<Movie> movies;
	
	private List<Category> categories;
	private List<Country> countries;
	private List<Language> languages;
	private List<Calendar> calendars;
	
	private List<Comment> comments;//不能直接用movie.getComments()，要用CommentService来取
	// 显示当前值用
	private Movie movie;
	private Image image;//显示当前图片
	private int[] categoriesSelected;
	private int[] countriesSelected;
	private int[] languagesSelected;
	
	// 逗号分隔的字符串，为了存储MDS传回来的值，以及和SERVER端交换数据用 (只有在一对多或多对多的时候才需要）
	
	private String imagesData;
	private String videosData;
	private String musicsData;
	private String mpacsData;
	private String mprsData;
	//
	private Paging paging = new Paging();// 必须先初始化，因为有可能URL中不含Paging相关的信息，那即为NULL

	//for deleting
	private MpacService mpacService;
	private MprService mprService;
	private VideoService videoService;
	private Mpac mpac;
	private Mpr mpr;
	private Video video;
	
	public String add() throws Exception {
		setMovie(null);
		
		movies = movieService.list(paging);

		countries = countryService.loadAll();
		categories = categoryService.loadAll();
		languages = languageService.loadAll();
		calendars = calendarService.loadAll();

		categoriesSelected = new int[0];
		countriesSelected = new int[0];
		languagesSelected = new int[0];

		imagesData = "";
		videosData = "";
		musicsData = "";
		mpacsData="";
		mprsData="";
		
		return Constants.ADD;
	}

	public String edit() throws Exception {
		setMovie(movieService.load(movie.getId()));
		
		movies = movieService.list(paging);
		countries = countryService.loadAll();
		categories = categoryService.loadAll();
		languages = languageService.loadAll();
		calendars = calendarService.loadAll();

		Set<Category> categories = (Set<Category>) movie.getCategories();
		categoriesSelected = new int[categories.size()];
		int i = 0;
		for (Category category : categories) {
			categoriesSelected[i++] = category.getId();
		}

		Set<Country> countries = (Set<Country>) movie.getCountries();
		countriesSelected = new int[countries.size()];
		i = 0;
		for (Country country : countries) {
			countriesSelected[i++] = country.getId();
		}

		Set<Language> languages = (Set<Language>) movie.getLanguages();
		languagesSelected = new int[languages.size()];
		i = 0;
		for (Language language : languages) {
			languagesSelected[i++] = language.getId();
		}

		// initialize directors and actors
		
		imagesData = "";
		videosData = "";
		musicsData = "";
		mpacsData="";
		mprsData="";
		

		Set<ImageMovie> images = movie.getImages();
		if (images != null) {
			for (Image image : images) {
				imagesData += image.getId() + OUT_SEPARATOR;
			}
		}

		Set<Video> videos = movie.getVideos();
		if (videos != null) {
			for (Video video : videos) {
				videosData += video.getId() + OUT_SEPARATOR;
			}
		}

		Set<Music> musics = movie.getMusics();
		if (musics != null) {
			for (Music music : musics) {
				musicsData += music.getId() + OUT_SEPARATOR;
			}
		}

		Set<Mpac> mpacs = movie.getMpacs();
		if (mpacs != null) {
			for (Mpac mpac : mpacs) {
				mpacsData += mpac.getCalendar().getId() + IN_SEPARATOR 
						+ mpac.getAward().getId() + IN_SEPARATOR
						+ (mpac.getPerson()==null?"":mpac.getPerson().getId())
						+ IN_SEPARATOR
						+ mpac.getType() + OUT_SEPARATOR;
			}
		}

		Set<Mpr> mprs = movie.getMprs();
		if (mprs != null) {
			for (Mpr mpr : mprs) {
				
				mprsData += mpr.getRole().getId() + "," 
						+ mpr.getPerson().getId() + OUT_SEPARATOR;
			}
		}
		
		
		return Constants.EDIT;
	}

	public String save() throws Exception {

		//edit
		if(movie.getId()!=0){
			Movie existingMovie = movieService.load(movie.getId());
			if(movie.getImage().getId()!=0){
				existingMovie.setImage(movie.getImage());
			}
			if(movie.getCalendar().getId()!=0){
				existingMovie.setCalendar(movie.getCalendar());
			}
			existingMovie.setMtimeId(movie.getMtimeId());
			existingMovie.setDoubanId(movie.getDoubanId());
			existingMovie.setName(movie.getName());
			existingMovie.setNameCn(movie.getNameCn());
			existingMovie.setAlias(movie.getAlias());
			existingMovie.setPlot(movie.getPlot());
			existingMovie.setLength(movie.getLength());
			existingMovie.setDatetime(movie.getDatetime());
			movie = existingMovie;
		}
		
		movie.setName(movie.getName().trim());
		movie.setNameCn(movie.getNameCn().trim());
		
		Set<Category> categories = new HashSet<Category>();
		for (int a : categoriesSelected) {
			Category category = new Category();
			category.setId(a);
			categories.add(category);

		}
		Set<Country> countries = new HashSet<Country>();
		for (int b : countriesSelected) {
			Country country = new Country();
			country.setId(b);
			countries.add(country);

		}
		Set<Language> languages = new HashSet<Language>();
		for (int c : languagesSelected) {
			Language language = new Language();
			language.setId(c);
			languages.add(language);

		}

		//		System.out.println("MovieAction.save() mprsData: " + mprsData);
		
//		imagesData = imagesData.replaceAll(";", ",");
//		videosData = videosData.replaceAll(";", ",");
//		musicsData = musicsData.replaceAll(";", ",");
//		
		String imageIds[] = imagesData.split(OUT_SEPARATOR);
		String videoIds[] = videosData.split(OUT_SEPARATOR);
		String musicIds[] = musicsData.split(OUT_SEPARATOR);
		

		if (!"".equals(imagesData)) {
			for (String id : imageIds) {
				if (!"".equals(id)) {
					ImageMovie image = new ImageMovie();
					image.setId(Integer.parseInt(id));
					movie.getImages().add(image);
				}
			}
		}
		if (!"".equals(videosData)) {
			for (String id : videoIds) {
				if (!"".equals(id)) {
					Video video = new Video();
					video.setId(Integer.parseInt(id));
					movie.getVideos().add(video);
					//video.setMovie(movie);//if inverse == true, this is required
				}
			}
		}

		if (!"".equals(musicsData)) {
			for (String id : musicIds) {
				if (!"".equals(id)) {
					Music music = new Music();
					music.setId(Integer.parseInt(id));
					movie.getMusics().add(music);
				}
				
			}
		}

		String mpacIds[] = mpacsData.split(OUT_SEPARATOR);// Calendar,Award,Person[-Calendar,Award,Person] : 1,1,1-2,3,4-2,2,2
		if (!"".equals(mpacsData)) {
			for (String mpacId : mpacIds) {
				
				if (!"".equals(mpacId)) {
					String ids[] = mpacId.split(IN_SEPARATOR);
					Mpac mpac = new Mpac();
					
					//movie
					mpac.setMovie(movie);
					
					//calendar
					Calendar calendar = new Calendar();
					calendar.setId(Integer.parseInt(ids[0]));
					mpac.setCalendar(calendar);
					
					//award
					Award award = new Award();
					award.setId(Integer.parseInt(ids[1]));
					mpac.setAward(award);
					
					//person (optional)
					if(!"".equals(ids[2])){
						Person person = new Person();
						person.setId(Integer.parseInt(ids[2]));
						mpac.setPerson(person);
					}
					
					//type
					mpac.setType(Integer.parseInt(ids[3]));
					
					movie.getMpacs().add(mpac);
				}
			}
		}

		
		String mprIds[] = mprsData.split(OUT_SEPARATOR);// Calendar,Award,Person[;Calendar,Award,Person] : 1,1,1;2,3,4;2,2,2
		if (!"".equals(mprsData)) {
			for (String mprId : mprIds) {
				if (!"".equals(mprId)) {
					String ids[] = mprId.split(IN_SEPARATOR);
					Mpr mpr = new Mpr();
					mpr.setMovie(movie);
					
					Role role = new Role();
					role.setId(Integer.parseInt(ids[0]));
					mpr.setRole(role);
					
					Person person = new Person();
					person.setId(Integer.parseInt(ids[1]));
					mpr.setPerson(person);
					
					movie.getMprs().add(mpr);
					
				}
			}
		}
		movie.setCategories(categories);
		movie.setCountries(countries);
		movie.setLanguages(languages);
		
		if(movie.getImage()==null || movie.getImage().getId()==0){
			movie.setImage(null);
		}
		
		for(Video video: movie.getVideos()){
			System.out.println(video.getId());
		}
		movieService.save(movie);

		return Constants.SUCCESS;
	}

	public String load() throws Exception {
		setMovie(movieService.load(movie.getId()));
		paging.setPageSize(10);
		comments = commentService.listByMovieId(movie.getId(), paging);
		return Constants.DETAIL;
	}

	public String images() throws Exception {
		
		setMovie(movieService.load(movie.getId()));
		
		if (image == null) {
			setImage(movie.getImage());
		} else {
			for (Image img : movie.getImages()) {
				if (image.getId() == img.getId()) {
					setImage(img);
					break;
				}
			}
		}
		
		return Constants.IMAGES;
	}
	public String videos() throws Exception {
		setMovie(movieService.load(movie.getId()));
		return Constants.VIDEOS;
	}
	public String list() throws Exception {
		
		if(movie!=null && !"".equals(movie.getName())){
			Movie m = new Movie();
			String n = movie.getName().trim();
			m.setName(n);
			m.setNameCn(n);
			
			movies = movieService.list(paging,m);
		} else {
			
			movies = movieService.list(paging);
		}
		
		return Constants.LIST;
	}

	public String deleteMpr() throws Exception {
		mpr = this.mprService.load(mpr.getId());
		this.movie.getMprs().remove(mpr);
		this.mprService.delete(mpr);
		return Constants.SUCCESS;
	}
	
	public String deleteVideo() throws Exception {
		//video = videoService.load(video.getId());
		//this.movie.getVideos().remove(video);
		this.videoService.delete(video);
		return Constants.SUCCESS;
	}
	
	public String deleteMpac() throws Exception {
		this.mpacService.delete(mpac);
		return Constants.SUCCESS;
	}
	
	
	// getters/setters//////////////////////////////////////////////////////////////////////////
	public void setMovieService(MovieService movieService) {
		this.movieService = movieService;
	}

	public MovieService getMovieService() {
		return movieService;
	}

	public List<Movie> getMovies() {
		return movies;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public CategoryService getCategoryService() {
		return categoryService;
	}

	public void setCountryService(CountryService countryService) {
		this.countryService = countryService;
	}

	public CountryService getCountryService() {
		return countryService;
	}

	public void setCategories(List<Category> categories) {
		this.categories = categories;
	}

	public List<Category> getCategories() {
		return categories;
	}

	public void setCountries(List<Country> countries) {
		this.countries = countries;
	}

	public List<Country> getCountries() {
		return countries;
	}

	public int[] getCategoriesSelected() {
		return categoriesSelected;
	}

	public void setCountriesSelected(int[] countriesSelected) {
		this.countriesSelected = countriesSelected;
	}

	public int[] getCountriesSelected() {
		return countriesSelected;
	}

	public void setMovie(Movie movie) {
		this.movie = movie;
	}

	public Movie getMovie() {
		return movie;
	}

	public void setLanguages(List<Language> languages) {
		this.languages = languages;
	}

	public List<Language> getLanguages() {
		return languages;
	}

	public LanguageService getLanguageService() {
		return languageService;
	}

	public void setLanguageService(LanguageService languageService) {
		this.languageService = languageService;
	}

	public int[] getLanguagesSelected() {
		return languagesSelected;
	}

	public void setLanguagesSelected(int[] languagesSelected) {
		this.languagesSelected = languagesSelected;
	}

	public void setCategoriesSelected(int[] categoriesSelected) {
		this.categoriesSelected = categoriesSelected;
	}

	public void setCalendarService(CalendarService calendarService) {
		this.calendarService = calendarService;
	}

	public CalendarService getCalendarService() {
		return calendarService;
	}

	public void setCalendars(List<Calendar> calendars) {
		this.calendars = calendars;
	}

	public List<Calendar> getCalendars() {
		return calendars;
	}

	public void setImagesData(String imagesData) {
		this.imagesData = imagesData;
	}

	public String getImagesData() {
		return imagesData;
	}

	public void setVideosData(String videosData) {
		this.videosData = videosData;
	}

	public String getVideosData() {
		return videosData;
	}

	public void setMusicsData(String musicsData) {
		this.musicsData = musicsData;
	}

	public String getMusicsData() {
		return musicsData;
	}

	public void setPaging(Paging paging) {
		this.paging = paging;
	}

	public Paging getPaging() {
		return paging;
	}

	public void setMpacsData(String mpacsData) {
		this.mpacsData = mpacsData;
	}

	public String getMpacsData() {
		return mpacsData;
	}

	public void setMprsData(String mprsData) {
		this.mprsData = mprsData;
	}

	public String getMprsData() {
		return mprsData;
	}

	public void setMprService(MprService mprService) {
		this.mprService = mprService;
	}

	public MprService getMprService() {
		return mprService;
	}
	public MpacService getMpacService() {
		return mpacService;
	}

	public void setMpacService(MpacService mpacService) {
		this.mpacService = mpacService;
	}

	public void setMpr(Mpr mpr) {
		this.mpr = mpr;
	}

	public Mpr getMpr() {
		return mpr;
	}

	public void setMpac(Mpac mpac) {
		this.mpac = mpac;
	}

	public Mpac getMpac() {
		return mpac;
	}

	public void setCount(int count) {
		this.scountss = count;
	}

	public int getCount() {
		return scountss++;
	}

	

	public void setImage(Image image) {
		this.image = image;
	}

	public Image getImage() {
		return image;
	}

	public void setVideoService(VideoService videoService) {
		this.videoService = videoService;
	}

	public VideoService getVideoService() {
		return videoService;
	}

	public void setVideo(Video video) {
		this.video = video;
	}

	public Video getVideo() {
		return video;
	}

	public void setPlotService(PlotService plotService) {
		this.plotService = plotService;
	}

	public PlotService getPlotService() {
		return plotService;
	}

	public void setCommentService(CommentService commentService) {
		this.commentService = commentService;
	}

	public CommentService getCommentService() {
		return commentService;
	}

	public void setComments(List<Comment> comments) {
		this.comments = comments;
	}

	public List<Comment> getComments() {
		return comments;
	}
}
